import React from 'react'
import { connect } from 'dva'
import PropTypes from 'prop-types'
import { Link } from 'dva/router'
import { Col, Form, Icon, Input, Button, Layout, message } from 'antd'

import { numvail } from '../utils/Validator.js'
import style from '../styles/login.less'
import reqwest from 'reqwest'

const FormItem = Form.Item
const { Footer } = Layout
// let _u = navigator.userAgent
// let isAndroid = _u.indexOf('Android') > -1 || _u.indexOf('Adr') > -1 //android终端
// let isiOS = !!_u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
class NormalLoginForm extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      username: '',
      password: '',
      loading: false
    }
  }
  handleSubmit(e) {
    let _this = this
    e.preventDefault()
    console.log(window.host + '/api/sessions')
    this.props.form.validateFields((err, values) => {
      if (!err) {
        _this.setState({ loading: true })
        reqwest({
          url: window.host + '/api/sessions',
          method: 'post',
          crossOrigin: true,
          type: 'json',
          data: { login: this.state.username, password: this.state.password }
        })
          .then(data => {
            if (data.status == 'success') {
              let set = {
                mobile: data.current_user.mobile,
                avatar: data.current_user.avatar,
                avatar_url: data.current_user.avatar_url,
                name: data.current_user.name,
                role: data.current_user.role,
                accout_name: data.current_user.account.account_name,
                accout_address: data.current_user.account.address,
                invit_url: data.current_user.account.invit_url
              }
              message.success('登录成功', 1, () => {
                window.localStorage['token'] = data.token
                window.localStorage['curloe'] = data.current_user.role
                // debugger
                window.localStorage['menu'] = JSON.stringify(data.menu)
                window.localStorage['cgj_id'] = data.current_user.cgj_user_id
                window.localStorage['account_type'] =
                  data.current_user.account_type
                window.localStorage['userrr_id'] = data.current_user.id
                window.localStorage['setting'] = JSON.stringify(set)
                // console.log(data.wallet)
                // window.localStorage['money'] = JSON.stringify(data.current_user.wallet)
                // window.localStorage['companies']=JSON.stringify(data.companies);
                window.sessionStorage['material'] = JSON.stringify(
                  data.materials
                )
                // window.sessionStorage['store_tree']=JSON.stringify(data.stores_tree);
                // window.sessionStorage['surveyors']=JSON.stringify(data.surveyors);
                // window.location.hash=window.location.hash
                // window.location.hash='/app/home?curren=1';
                if (data.current_user.role === 'acct') {
                  _this.context.router.replace('/app/pay?current=1')
                } else {
                  _this.context.router.replace('/app/home?current=1')
                }
              })
            } else {
              _this.setState({ loading: false })
              message.error(data.msg)
            }
          })
          .fail((err, msg) => {
            _this.setState({ loading: false })
            message.error('当前没有网络连接 或者 服务君挂了哦')
          })
      }
    })
  }
  componentWillMount() {
    let c = window.location.search

    // alert(navigator)
    if (c.match(/code/) == ['code']) {
      let a = window.location.search.match(/\=\w+/)
      let b = a[0].match(/\w+/)
      reqwest({
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
        method: 'get',
        crossOrigin: true,
        data: {
          appid: 'wx1211e96e6c279899',
          secret: '92638679efd96e9033fcbecf62eed460',
          code: b[0],
          grant_type: 'authorization_code'
        },
        type: 'json'
      })
        .then(data => {
          console.log(data)
        })
        .fail(data => {
          console.log(data)
        })
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form
    const { username, password } = this.state
    // <a className="login-form-forgot" href="">忘记密码? </a>

    return <Layout className={`${style.auth}`}>
        <Col className={`${style.auth_content}`}>
          <h1>登录管家快销</h1>
          <Form className={`${style.auth_form}`} onSubmit={this.handleSubmit.bind(this)}>
            <FormItem className={`${style.input_group}`}>
              {getFieldDecorator('userName', {
                rules: [
                  {
                    required: true,
                    len: 11,
                    message: '请输入正确的手机号',
                    validator: (rule, value, callback) => {
                      numvail(rule, value, callback)
                    }
                  }
                ]
              })(<Input onChange={e => {
                    this.setState({ username: e.target.value })
                  }} prefix={<Icon type="user" style={{ fontSize: 14 }} />} placeholder="请输入用户账号" />)}
            </FormItem>
            <FormItem className={`${style.input_group}`}>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码' }]
              })(<Input onChange={e => {
                    this.setState({ password: e.target.value })
                  }} prefix={<Icon type="lock" style={{ fontSize: 14 }} />} type="password" placeholder="请输入用户密码" />)}
            </FormItem>
            <FormItem className={`${style.input_group}`}>
              <Button loading={this.state.loading} type="primary" htmlType="submit" className={`${style.submit_btn}`}>
                登录
              </Button>
            </FormItem>
            <FormItem className={`${style.links}`}>
              {/* to={{ pathname: '/register' }} */}
              <Link style={{ textAlign: 'center' }}>忘记密码</Link>
              |
              <Link to={{ pathname: '/reg' }}>用户注册</Link>
            </FormItem>
          </Form>
        </Col>
      </Layout>
  }
}
NormalLoginForm.contextTypes = {
  router: PropTypes.object
}
const WrappedNormalLoginForm = Form.create()(NormalLoginForm)

export default connect()(WrappedNormalLoginForm)
